<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培训类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择培训类型" clearable>
          <el-option label="售前" value="pre_sales"></el-option>
          <el-option label="售中" value="in_sales"></el-option>
          <el-option label="售后" value="after_sales"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="章节名称" prop="chapter">
        <el-input
          v-model="queryParams.chapter"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入课程编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:training:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:training:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading">
      <div v-for="(items, type) in groupedTrainings" :key="type" class="training-group">
        <h3 v-if="items.length > 0" class="group-title">{{ typeFormat({type}) }}</h3>
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in items" :key="item.id" style="margin-bottom: 20px;">
            <el-card shadow="hover" style="cursor: pointer;">
              <router-link :to="'/training/detail/' + item.id" style="text-decoration: none; color: inherit;">
                <div>
                  <image-preview :src="item.coverImage" :width="'100%'" :height="'150px'"/>
                  <div style="padding: 14px;">
                    <span>{{ item.chapter }}</span>
                    <div class="bottom clearfix" style="margin-top: 10px;">
                      <time class="time" style="color: #999; font-size: 13px;">{{ item.code }}</time>
                    </div>
                  </div>
                </div>
              </router-link>
              <div style="border-top: 1px solid #ebeef5; padding: 5px 14px; text-align: right;">
                <el-button type="text" icon="el-icon-edit" @click.stop="handleUpdate(item)" v-hasPermi="['system:training:edit']">修改</el-button>
                <el-button type="text" icon="el-icon-delete" @click.stop="handleDelete(item)" v-hasPermi="['system:training:remove']">删除</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改培训课程资料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="培训类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择培训类型">
            <el-option label="售前" value="pre_sales"></el-option>
            <el-option label="售中" value="in_sales"></el-option>
            <el-option label="售后" value="after_sales"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节名称" prop="chapter">
          <el-input v-model="form.chapter" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="课程编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入课程编号" />
        </el-form-item>
        <el-form-item label="视频" prop="videoName">
          <file-upload v-model="form.videoUrl" :on-success="handleVideoUploadSuccess" :file-list="videoList" :limit="1" :file-size="5120" :file-type="['mp4', 'mov', 'avi', 'wmv', 'flv']" />
        </el-form-item>
        <el-form-item label="文字讲解内容" prop="textExplanation">
          <el-input v-model="form.textExplanation" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面图片链接/路径" prop="coverImage">
          <image-upload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="主要知识点" prop="keyPoints">
          <el-input v-model="form.keyPoints" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTraining, getTraining, delTraining, addTraining, updateTraining } from "@/api/system/training";
import FileUpload from '@/components/FileUpload';
import ImageUpload from '@/components/ImageUpload';
import ImagePreview from '@/components/ImagePreview';

export default {
  name: "Training",
  components: { FileUpload, ImageUpload, ImagePreview },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训课程资料表格数据
      trainingList: [],
      // 分组后的培训资料
      groupedTrainings: {},
      // 视频文件列表
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        chapter: null,
        code: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "培训类型不能为空", trigger: "change" }
        ],
        chapter: [
          { required: true, message: "章节名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "课程编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    typeFormat(row) {
      if (row.type === 'pre_sales') return '售前';
      if (row.type === 'in_sales') return '售中';
      if (row.type === 'after_sales') return '售后';
      return '其他';
    },
    /** 查询培训课程资料列表 */
    getList() {
      this.loading = true;
      // 为了在分组视图下展示所有数据，您可以考虑调整分页参数，或者在后端提供一个不分页的接口
      // 这里我们暂时还是使用分页
      listTraining(this.queryParams).then(response => {
        this.trainingList = response.rows;
        this.total = response.total;
        this.groupTrainings();
        this.loading = false;
      });
    },
    // 分组培训资料
    groupTrainings() {
      const grouped = {
        pre_sales: [],
        in_sales: [],
        after_sales: []
      };
      this.trainingList.forEach(item => {
        if (item.type && grouped[item.type]) {
          grouped[item.type].push(item);
        }
      });
      this.groupedTrainings = grouped;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        chapter: null,
        code: null,
        videoUrl: null,
        videoName: null,
        videoId: null,
        textExplanation: null,
        coverImage: null,
        keyPoints: null,
      };
      this.videoList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训课程资料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getTraining(id).then(response => {
        this.form = response.data;
        this.videoList = [];
        if (response.data.videoName && response.data.videoUrl) {
          this.videoList.push({ name: response.data.videoName, url: response.data.videoUrl });
        }
        this.open = true;
        this.title = "修改培训课程资料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTraining(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTraining(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 视频上传成功回调 */
    handleVideoUploadSuccess(response, file) {
      if (response.code === 200) {
        this.form.videoId = response.data.fileId;
        this.form.videoUrl = response.data.url;
        this.form.videoName = this.form.chapter + '-' + this.form.code;
        this.videoList = [{ name: response.data.name, url: response.data.url }];
      } else {
        this.$modal.msgError(response.msg);
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除章节为"' + row.chapter + '"的数据项？').then(function() {
        return delTraining(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/training/export', {
        ...this.queryParams
      }, `training_${new Date().getTime()}.xlsx`);
    },
    /** 跳转到详情页 */
    handleChapterClick(item) {
        this.$router.push(`/training/detail/${item.id}`);
    }
  }
};
</script>
<style scoped>
.training-group .group-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}
</style>
